# encoding=utf-8
# pip install pyserial -i https://pypi.tuna.tsinghua.edu.cn/simple
# Connect:
#    B- --> B-
#    A+ --> A+
#   GND --> GND
import time
import serial
import logging
import traceback
from SerialTools import _crc8_impl


class SerialBaseCommand:
    # IO Control
    OUT = 0x01
    QUERY = 0x02
    IN = 0x03

    # IO IN/OUT Response
    ACK = 0x01
    ERROR = 0x02

    # IO QUERY
    QUERY_PENDING = 0x01
    QUERY_DONE = 0x02
    QUERY_ERROR = 0x03

    # tools
    def get_command_byte(self, command: int):
        return command.to_bytes(1, 'big')


class SerialBase(SerialBaseCommand):
    def __init__(self, device: str, rate: int = 115200):
        # serial port
        self.serial = serial.Serial(device, rate, timeout=1)
        if not self.serial.is_open:
            raise IOError("Can't open {}, check connect or permission".format(device))

    def release(self):
        if not self.serial.is_open:
            self.serial.close()

    ####   Basic serial cache clean   ####
    def _clean_serial_cache(self):
        self.serial.flush()

    def _make_sure_flush(self):
        self._clean_serial_cache()
        cache_len = self.serial.in_waiting
        if cache_len > 0:
            self._read_raw_data(cache_len)

    ####   Basic Read and Write   ####
    def _send_raw_data(self, byte_data: bytes):
        try:
            self.serial.write(byte_data)
            return True
        except Exception as e:
            logging.error(traceback.format_exc())
            return False

    def _read_raw_data(self, data_len: int):
        try:
            return self.serial.read(data_len)
        except Exception as e:
            logging.error(traceback.format_exc())
            return None

    ####   Basic crc tools   ####
    def _crc8(self, byte_data):
        return _crc8_impl(byte_data)




if __name__ == '__main__':
    base = SerialBase("/dev/ttyACM0")
    print(base._crc8(b'hello world'))
        